package com.example.cardgame

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.GridLayout
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.children
import cn.edu.sicnu.cardgame.CardMatchingGame

class GameActivity : AppCompatActivity(),View.OnClickListener{

    lateinit var game: CardMatchingGame
    val cardButtons=mutableListOf<Button>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_game)
        Log.d("life cycle","onCreate")
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) {
                v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        val gridLayout: GridLayout =findViewById(R.id.card)
        val reset: Button=findViewById(R.id.reset)

        for (v in gridLayout.children){
            if (v is Button){
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }

        game=CardMatchingGame(cardButtons.count())
        updateUI()

        reset.setOnClickListener{
            game=CardMatchingGame(cardButtons.count())
            val score=findViewById<TextView>(R.id.score)
            val intent=Intent()
            val str=score.text.toString().split(":")
            intent.putExtra("SECOND_MSG",str[1])
            setResult(1,intent)
            updateUI()
        }
        val rmain = findViewById<Button>(R.id.rmain)
        rmain.setOnClickListener {
            finish()
        }

    }
    @SuppressLint("ResourceAsColor", "DefaultLocale")
    fun updateUI(){
        for (button in cardButtons){
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if (card.isChosen) {
                button.text = card.toString()
                button.setBackgroundColor(Color.White.toArgb())
            } else {
                button.text = ""
                button.setBackgroundResource(R.drawable.cslogo) // 设置未翻开卡片的背景为图片
            }
        }
        val score = findViewById<TextView>(R.id.score)
        score.text = String.format("%s%d", "score:", game.score)
    }

    override fun onClick(v: View?) {
        if (v is Button){
            val index=cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }
}